//
//  MyStreetListViewController.m
//  homeland
//
//  Created by SunShine on 13-10-23.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "MyStreetListViewController.h"
#import "MapViewController.h"
//#import "AdvisoryViewController.h"
#import "StreetAdvisoryViewController.h"

@interface MyStreetListViewController ()
@property (strong, nonatomic) MyStreetService *dataService;
@property (strong, nonatomic) NSString *phoneToCall;
@property (strong, nonatomic) CustomPullToRefresh *ptr;
@property (strong, nonatomic) NSString *key;
@end

@implementation MyStreetListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configVC];
    self.navigationItem.rightBarButtonItem = nil;
}

-(void)backMethod
{
    //重写返回上级的方法，在返回前先清理下内存
    _dataService.dataList = nil;
    self.dataService = nil;
    [super backMethod];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Config View
-(void)configVC
{
    self.key = [_config objectForKey:@"key"];
    NSLog(@"进入ListView的key是%@",_key);
    //读取配置文件
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"MyStreet_ListPages" ofType:@"plist"];
    NSDictionary *listPageConfigs = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
    self.config  = [listPageConfigs objectForKey:_key];
    //产生数据服务对象
    self.dataService = [MyStreetService new];
    _dataService.delegate = self;
    _dataService.queryKey = self.key;
    //显示标题
    self.title = [_config objectForKey:@"title"];
    //控制搜索栏
    BOOL searchBarFlag = [(NSNumber *)[_config objectForKey:@"searchBar"] boolValue];
    if (searchBarFlag) {//根据配置决定是否有搜索框
        self.searchBar.hidden = NO;
        self.searchBar.placeholder = [NSString stringWithFormat:@"请输入%@名称",_key];
        self.searchBar.delegate = self;
        self.searchBar.inputAccessoryView = [self getInputAccessoryView];
        self.searchBar.hidden = NO;
    } else {
        self.searchBar.hidden = YES;
        //隐藏搜索框之后，调整table的位置
        CGRect tableFrame = _tableView.frame;
        tableFrame.origin.y = tableFrame.origin.y - CGRectGetHeight(_searchBar.frame);
        tableFrame.size.height = tableFrame.size.height + CGRectGetHeight(_searchBar.frame);
        _tableView.frame = tableFrame;
    }
    
    //控制segment
    NSArray *segment = [_config objectForKey:@"segment"];
    if (segment && segment.count > 0) {
        //有segment
        self.segment = [[HMSegmentedControl alloc]initWithSectionTitles:segment];
        _segment.hidden = NO;
        _segment.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _segment.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        _segment.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segment.scrollEnabled = NO;
        [_segment setFrame:CGRectMake(0, 0, 320, 44)];
        [_segment addTarget:self action:@selector(segmentValueChanged) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_segment];
        //控制参数
        _dataService.queryKey = [NSString stringWithFormat:@"%@-%@", self.key, [segment objectAtIndex:0]];
        //调整searchbar和table
        CGRect searchFrame = _searchBar.frame;
        searchFrame.origin.y = searchFrame.origin.y + CGRectGetHeight(_segment.frame);
        _searchBar.frame = searchFrame;
        CGRect tableFrame = _tableView.frame;
        tableFrame.origin.y = tableFrame.origin.y + CGRectGetHeight(_segment.frame);
        tableFrame.size.height = tableFrame.size.height - CGRectGetHeight(_segment.frame);
        _tableView.frame = tableFrame;
    }
    //开启下拉刷新
    self.ptr = [[CustomPullToRefresh alloc]initWithScrollView:self.tableView delegate:self];
    //开始读取数据
    [self startLoadingView];
    [self.dataService loadDataWithKey:nil];
}
#pragma mark - Table Datasource Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataService.dataList?[_dataService.dataList count]:0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_dataService heightForCellAtRow:indexPath];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellName = [_config objectForKey:@"cellClassName"];
    Class cellClass =  NSClassFromString(cellName);
    if (!cellClass) {
        NSLog(@"cellClass%@类型不正确",cellName);
        return nil;
    }
    static NSString *cellIdentifier = @"ListViewCell";
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:cellName owner:self options:nil]objectAtIndex:0];
    }
    
    [_dataService configCell:cell atIndex:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [self.dataService getTargetConfigForCellAtIndex:indexPath];
    if (!dic) {
        NSLog(@"未能获取到配置,无法进入下一页面");
        return;
    }
    //产生下一级页面
    Class tempClass =  NSClassFromString([_config objectForKey:@"targetClassName"]);
    if (!tempClass) {
        NSLog(@"target%@类型不正确",[_config objectForKey:@"targetClassName"]);
        return;
    }
    ConfigableViewController *vc = [[tempClass alloc]initWithNibName:[_config objectForKey:@"targetClassName"] bundle:nil];
    vc.config = dic;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Segment Delegate
-(void)segmentValueChanged
{
    NSInteger selected = self.segment.selectedSegmentIndex;
    NSLog(@"selected segment index:%d",selected);
    self.searchBar.text = @"";
    NSArray *segment = [_config objectForKey:@"segment"];
    _dataService.queryKey = [NSString stringWithFormat:@"%@-%@", self.key, [segment objectAtIndex:selected]];
    [self startLoadingView];
    [self.dataService loadDataWithKey:nil];
}

#pragma mark - Search Bar Delegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"search bar input:%@",searchText);
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"search button clicked with input:%@",searchBar.text);
    [searchBar resignFirstResponder];
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    NSLog(@"search bar end edit with input %@",searchBar.text);
    [self startLoadingView];
    if (searchBar.text.length == 0) {
        //如果没输入内容并且点击完成，则重新刷新列表
        [self.dataService loadDataWithKey:nil];
    } else {
        [self.dataService loadDataWithKey:searchBar.text];
    }
}

#pragma mark - Alert View Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == PHONE_ALERT_TAG) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",_phoneToCall]]];
        }
    }
}

#pragma mark - Buttons Action
-(void)advisoryButtonAction:(id)sender
{
    NSLog(@"点击了咨询按钮");
    StreetAdvisoryViewController *advisoryVC = [[StreetAdvisoryViewController alloc]initWithNibName:@"StreetAdvisoryViewController" bundle:nil];
    NSInteger index = ((UIButton *)sender).tag;
    advisoryVC.currentTitle=[_config objectForKey:@"title"];
    CommonMineQueryItem *item = [_dataService.dataList objectAtIndex:index];
    advisoryVC.config = [NSDictionary dictionaryWithObject:item forKey:@"dataItem"];
    [self.navigationController pushViewController:advisoryVC animated:YES];
}

-(void)phoneButtonAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSObject *item = [self.dataService.dataList objectAtIndex:btn.tag];
    NSString* phone = [item valueForKey:@"phone"];
    if ([phone rangeOfString:@","].location != NSNotFound) {
        NSLog(@"准备截断电话号码%@",phone);
        phone = [phone substringToIndex:[phone rangeOfString:@","].location];
    }
    NSLog(@"点击了电话按钮%@",phone);
    self.phoneToCall = phone;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString  stringWithFormat:@"您是否需要拨打电话%@",phone] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = PHONE_ALERT_TAG;
    [alert show];
    //    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];
}

-(void)mapButtonAction:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSObject *item = [self.dataService.dataList objectAtIndex:btn.tag];
    NSString* point = [item valueForKey:@"point"];
    NSLog(@"点击了地图按钮%@",point);
    //go into map view
    MapViewController *mapViewController = [[MapViewController alloc]initWithNibName:@"MapViewController" bundle:nil];
    [self.navigationController pushViewController:mapViewController animated:YES];
    double longitude = [point substringToIndex:[point rangeOfString:@"|"].location].floatValue;
    double latitude = [point substringFromIndex:[point rangeOfString:@"|"].location + 1].floatValue;
    [mapViewController showMaskWithLatitude:latitude Longitude:longitude];
}

#pragma mark - Data Service Delegate
-(void)loadDataFinished
{
    [self stopLoadingView];
    [self.ptr endRefresh];
    [self.tableView reloadData];
}

-(void)loadDataFaild:(NSString *)msg
{
    [self stopLoadingView];
    [self.ptr endRefresh];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)setEnableToLoadMore:(BOOL)enable
{
    self.ptr.enablePullToBottom = enable;
}

#pragma mark - PullToRefresh Method
//捕获到拉动事件
-(void)customPullToRefreshShouldRefresh:(CustomPullToRefresh *)ptr withDirection:(MSRefreshDirection)direction
{
    NSLog(@"捕获到拉动事件");
    if (direction == MSRefreshDirectionTop) {
        if (self.searchBar.text == 0) {
            [self.dataService loadDataWithKey:nil];
        } else {
            [self.dataService loadDataWithKey:self.searchBar.text];
        }
    }
    if (direction == MSRefreshDirectionBottom) {
        if (self.searchBar.text == 0) {
            [self.dataService loadMoreDataWithKey:nil];
        } else {
            [self.dataService loadMoreDataWithKey:self.searchBar.text];
        }
    }
}
@end
